<template>
  <div class="app-container">
    <div class="header-info">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/system/dataset' }">数据集列表</el-breadcrumb-item>
        <el-breadcrumb-item>{{ datasetInfo.datasetName }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="header-actions">
        <el-button type="primary" @click="handleBack" size="small">
          <i class="el-icon-arrow-left"></i>
          返回
        </el-button>
        <el-button type="info" @click="handleRefresh" size="small" :loading="refreshing">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
        <el-button type="success" @click="handleExport" size="small" :loading="exporting">
          <i class="el-icon-download"></i>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 数据集信息卡片 -->
    <el-card class="dataset-info-card">
      <div class="dataset-info">
        <div class="info-item">
          <span class="info-label">数据集名称：</span>
          <span class="info-value">{{ datasetInfo.datasetName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">数据集编码：</span>
          <span class="info-value">{{ datasetInfo.datasetCode }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">数据集类型：</span>
          <span class="info-value">{{ getDatasetTypeName(datasetInfo.datasetType) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">数据源：</span>
          <span class="info-value">{{ datasetInfo.datasourceName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">状态：</span>
          <span class="info-value">
            <el-tag :type="datasetInfo.status === '0' ? 'success' : 'danger'">
              {{ datasetInfo.status === '0' ? '启用' : '停用' }}
            </el-tag>
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">版本：</span>
          <span class="info-value">{{ datasetInfo.version }}</span>
        </div>
      </div>
    </el-card>

    <!-- 查询参数配置 -->
    <el-card class="query-params-card" v-if="!isDatasetLoading">
      <template #header>
        <div class="card-header">
          <span>查询参数</span>
          <el-button type="text" @click="toggleParamsVisible" size="small">
            {{ paramsVisible ? '收起' : '展开' }}
            <i :class="{ 'el-icon-arrow-up': paramsVisible, 'el-icon-arrow-down': !paramsVisible }"></i>
          </el-button>
        </div>
      </template>

      <div v-show="paramsVisible" class="query-params-form">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
          <template v-for="(param, index) in dynamicParams" :key="index">
            <el-form-item :label="param.label" :prop="param.field">
              <el-input v-if="param.type === 'string'" v-model="queryParams[param.field]"
                :placeholder="`请输入${param.label}`" maxlength="100" />
              <el-input-number v-else-if="param.type === 'number'" v-model="queryParams[param.field]"
                :min="param.min || 0" :max="param.max || 999999" :placeholder="`请输入${param.label}`" />
              <el-select v-else-if="param.type === 'select'" v-model="queryParams[param.field]"
                :placeholder="`请选择${param.label}`">
                <el-option v-for="option in param.options" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
              <el-date-picker v-else-if="param.type === 'date'" v-model="queryParams[param.field]" :type="'date'"
                :placeholder="`请选择${param.label}`" />
              <el-date-picker v-else-if="param.type === 'datetime'" v-model="queryParams[param.field]"
                :type="'datetime'" :placeholder="`请选择${param.label}`" />
            </el-form-item>
          </template>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据预览内容 -->
    <div class="preview-content" v-if="!isDatasetLoading">
      <div class="preview-controls">
        <div class="display-format">
          <span>显示格式：</span>
          <el-radio-group v-model="displayFormat" @change="handleFormatChange">
            <el-radio-button label="table">表格</el-radio-button>
            <el-radio-button label="json">JSON</el-radio-button>
          </el-radio-group>
        </div>

        <div class="record-limit">
          <span>每页记录数：</span>
          <el-select v-model="pageSize" @change="handlePageSizeChange" style="width: 100px;">
            <el-option v-for="size in pageSizes" :key="size" :label="size" :value="size" />
          </el-select>
        </div>
      </div>

      <!-- 表格格式展示 -->
      <div v-if="displayFormat === 'table'" class="table-preview">
        <el-table :data="previewData" style="width: 100%" border v-loading="loading"
          :header-cell-style="headerCellStyle" :cell-style="cellStyle">
          <template v-for="(column, index) in columns" :key="index">
            <el-table-column :prop="column.property" :label="column.label" :width="getColumnWidth(column)"
              :type="getColumnType(column)" :formatter="getColumnFormatter(column)">
              <template #default="scope">
                <el-tooltip :content="formatCellValue(scope.row[column.property])" placement="top"
                  :disabled="!needsTooltip(scope.row[column.property])">
                  <span>{{ formatCellDisplay(scope.row[column.property]) }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>

      <!-- JSON格式展示 -->
      <div v-else-if="displayFormat === 'json'" class="json-preview">
        <el-card class="json-content" v-loading="loading">
          <pre>{{ formatJson(previewData) }}</pre>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="pageSizes"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePageSizeChange"
          @current-change="handlePageChange" />
      </div>
    </div>

    <!-- 加载中 -->
    <div v-else class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
  </div>
</template>

<script>
import { getDatasetById, previewDatasetData } from "@/api/system/dataset";

export default {
  name: "DatasetPreview",
  components: {
    data() {
      return {
        // 数据集信息
        datasetInfo: {
          datasetId: null,
          datasetName: "",
          datasetCode: "",
          datasetType: "",
          datasourceId: "",
          datasourceName: "",
          status: "0",
          version: ""
        },
        // 数据集类型映射
        datasetTypeMap: {
          "table": "表",
          "view": "视图",
          "query": "SQL查询",
          "api": "API"
        },
        // 加载状态
        loading: false,
        refreshing: false,
        exporting: false,
        isDatasetLoading: true,
        // 数据预览
        previewData: [],
        columns: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        // 显示格式
        displayFormat: "table",
        // 查询参数
        paramsVisible: false,
        queryParams: {},
        dynamicParams: []
      };
    },
    created() {
      this.init();
    },
    methods: {
      // 初始化
      init() {
        const datasetId = this.$route.params.datasetId;
        if (datasetId) {
          this.datasetInfo.datasetId = datasetId;
          this.getDatasetInfo();
        } else {
          this.$modal.msgError("参数错误，未找到数据集ID");
          this.handleBack();
        }
      },
      // 获取数据集信息
      getDatasetInfo() {
        getDatasetById(this.datasetInfo.datasetId)
          .then(response => {
            if (response.code === 200) {
              this.datasetInfo = response.data;
              // 初始化查询参数
              this.initQueryParams();
              // 加载预览数据
              this.loadPreviewData();
            } else {
              this.$modal.msgError(response.msg || "获取数据集信息失败");
              this.handleBack();
            }
            this.isDatasetLoading = false;
          })
          .catch(error => {
            this.isDatasetLoading = false;
            this.$modal.msgError("获取数据集信息失败: " + (error.message || "未知错误"));
            this.handleBack();
          });
      },
      // 初始化查询参数
      initQueryParams() {
        // 根据数据集类型初始化查询参数
        if (this.datasetInfo.datasetType === "query") {
          // 解析SQL获取参数（这里简化处理，实际可能需要更复杂的SQL解析）
          this.dynamicParams = [];
          // 示例参数，实际应从SQL或元数据中解析
          this.queryParams = {};
        }
      },
      // 加载预览数据
      loadPreviewData() {
        this.loading = true;

        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.queryParams
        };

        previewDatasetData(this.datasetInfo.datasetId, params)
          .then(response => {
            if (response.code === 200) {
              this.previewData = response.data.rows || [];
              this.columns = response.data.columns || [];
              this.total = response.data.total || 0;

              // 如果没有数据，尝试自动加载第一页
              if (this.previewData.length === 0 && this.currentPage > 1) {
                this.currentPage = 1;
                this.loadPreviewData();
              }
            } else {
              this.$modal.msgError(response.msg || "获取预览数据失败");
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
            this.$modal.msgError("获取预览数据失败: " + (error.message || "未知错误"));
          });
      },
      // 获取数据集类型名称
      getDatasetTypeName(type) {
        return this.datasetTypeMap[type] || type;
      },
      // 切换参数显示
      toggleParamsVisible() {
        this.paramsVisible = !this.paramsVisible;
      },
      // 处理查询
      handleQuery() {
        this.currentPage = 1;
        this.loadPreviewData();
      },
      // 重置查询
      resetQuery() {
        this.$refs.queryForm.resetFields();
        this.initQueryParams();
        this.currentPage = 1;
        this.loadPreviewData();
      },
      // 处理格式变更
      handleFormatChange() {
        // 格式变更时重新加载数据
        this.loadPreviewData();
      },
      // 处理页码变更
      handlePageChange(current) {
        this.currentPage = current;
        this.loadPreviewData();
      },
      // 处理每页条数变更
      handlePageSizeChange(size) {
        this.pageSize = size;
        this.currentPage = 1;
        this.loadPreviewData();
      },
      // 处理刷新
      handleRefresh() {
        this.refreshing = true;
        this.loadPreviewData().then(() => {
          this.refreshing = false;
        }).catch(() => {
          this.refreshing = false;
        });
      },
      // 处理导出
      handleExport() {
        this.exporting = true;
        // 这里应该调用导出接口，简化处理
        setTimeout(() => {
          this.$modal.msgSuccess("导出成功");
          this.exporting = false;
        }, 1000);
      },
      // 返回
      handleBack() {
        this.$router.push("/system/dataset");
      },
      // 获取列宽度
      getColumnWidth(column) {
        // 根据列名长度和数据类型设置默认宽度
        const defaultWidth = Math.min(Math.max(column.label.length * 12 + 20, 100), 200);
        return defaultWidth;
      },
      // 获取列类型
      getColumnType(column) {
        // 可以根据数据类型返回不同的列类型
        return 'default';
      },
      // 获取列格式化函数
      getColumnFormatter(column) {
        return (row, column, cellValue, index) => {
          return this.formatCellDisplay(cellValue);
        };
      },
      // 格式化单元格显示值
      formatCellDisplay(value) {
        if (value === null || value === undefined) {
          return "-";
        }

        // 格式化日期时间
        if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
          return this.formatDateTime(value);
        }

        // 格式化长文本
        if (typeof value === 'string' && value.length > 50) {
          return value.substring(0, 50) + "...";
        }

        // 格式化JSON对象
        if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
          return JSON.stringify(value).substring(0, 50) + (JSON.stringify(value).length > 50 ? "..." : "");
        }

        return value;
      },
      // 格式化单元格完整值
      formatCellValue(value) {
        if (value === null || value === undefined) {
          return "-";
        }

        // 格式化日期时间
        if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
          return this.formatDateTime(value);
        }

        // 格式化JSON对象
        if (typeof value === 'object' && value !== null) {
          return JSON.stringify(value, null, 2);
        }

        return String(value);
      },
      // 判断是否需要显示tooltip
      needsTooltip(value) {
        if (value === null || value === undefined) {
          return false;
        }

        // 长文本、对象、数组需要tooltip
        if (typeof value === 'string' && value.length > 50) {
          return true;
        }

        if (typeof value === 'object' && value !== null) {
          return true;
        }

        return false;
      },
      // 格式化日期时间
      formatDateTime(dateTime) {
        const date = new Date(dateTime);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      },
      // 格式化JSON显示
      formatJson(data) {
        try {
          return JSON.stringify(data, null, 2);
        } catch (error) {
          return "Invalid JSON data";
        }
      },
      // 表格样式
      headerCellStyle() {
        return {
          background: '#f5f7fa',
          fontWeight: 'bold'
        };
      },
      // 单元格样式
      cellStyle() {
        return {
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        };
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.dataset-info-card {
  margin-bottom: 20px;
}

.dataset-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.info-label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.info-value {
  color: #303133;
}

.query-params-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-params-form {
  margin-top: 10px;
}

.preview-content {
  margin-top: 20px;
}

.preview-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.display-format,
.record-limit {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-preview {
  margin-bottom: 20px;
}

.json-preview {
  margin-bottom: 20px;
}

.json-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  max-height: 500px;
  overflow-y: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.loading-container {
  padding: 20px;
}

@media (max-width: 768px) {
  .header-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .preview-controls {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .dataset-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-item {
    min-width: 100%;
  }
}
</style>
